﻿// HSS.Security.Program.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       Program.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/04/2010
// ----------------------------------------------------------------------------
namespace HSS.Security
{
	#region Using Directives
	using System;
	using System.Text;
	using System.Windows.Forms;
	using HSS.Forms;
	#endregion

	#region Program
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[System.STAThread]
		static void Main()
		{
			System.AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
			using (var ctx = new AppContext<KeyManager>())
			{
				ctx.RestoreLocation = false;
				ctx.RestoreSize = false;
				ctx.RestoreState = false;
				ctx.Run(null, InitApp);
			}
		}
		private static KeyManager InitApp(string[] args, AppContext<KeyManager> ctx)
		{
			ctx.ShowError += new EventHandler<SendExceptionEventArgs>(App_ShowError);
			ctx.SendException += new EventHandler<SendExceptionEventArgs>(App_SendException);
			return new KeyManager();
		}
		private static void App_ShowError(object sender, SendExceptionEventArgs e)
		{
			MessageBox.Show(e.UnhandledException.ToString(), "Exception Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
		}
		private static void App_SendException(object sender, SendExceptionEventArgs e)
		{
			if (e.SendException)
				SendException(e.UnhandledException);

			if (e.RestartApp)
				Application.Restart();
		}
		private static void SendException(Exception ex)
		{
			SendException(ex.ToString());
		}
		private static void SendException(string message)
		{
			System.Threading.ThreadPool.QueueUserWorkItem(SendException, message);
		}
		private static void SendException(object objMessage)
		{
			try
			{
				var builder = new StringBuilder(objMessage.ToString());
				builder.AppendLine();
				builder.AppendLine();
				AppContext<KeyManager>.AppendAppContextInfo(builder);
				builder.AppendLine();
				builder.AppendLine();
				AppContext<KeyManager>.AppendEnvironmentInfo(builder);
				var subject = Application.ProductName + ": Unhandled exception";
				var msg = new System.Net.Mail.MailMessage("support@highspeed-solutions.net", "support@highspeed-solutions.net", subject, builder.ToString());
				HSS.Net.Mail.SmtpClient.SendEmail(msg);
			}
			catch { }
		}
	}
	#endregion
}